% SingleSound.m

function res = SingleSound(fre, SampRate, amplitude, durat)
% SingleSound: 单个乐音生成器（叠加第一、二泛音列）
% fre: 乐音频率
% SampRate: 采样率
% amplitude: 乐音幅值（持续时幅值）
% durat: 乐音时长（单位：秒）
% res: 返回以正弦波为基础的幅值发生衰减的采样后的离散值
%      大小[时长*采样率 + 1， 1]

    load("ConstantDefinition.mat", "HarmAmp1", "HarmAmp2");
    res = SingleFre(fre, SampRate, amplitude, durat) + ...
        HarmAmp1 * SingleFre(fre*2, SampRate, amplitude, durat) + ...
        HarmAmp2 * SingleFre(fre*3, SampRate, amplitude, durat);
end

function res = SingleFre(fre, SampRate, amplitude, durat)
% SingleFre: 单频率乐音生成器
% fre: 乐音频率
% SampRate: 采样率
% amplitude: 乐音幅值（持续时幅值）
% durat: 乐音时长（单位：秒）
% res: 返回以正弦波为基础的幅值发生衰减的采样后的离散值
%      大小[时长*采样率 + 1， 1]

    res = zeros(ceil(durat * SampRate), 1);
    load("ConstantDefinition.mat", "PHI", "TurnPoint1", "TurnPoint2", "TurnPoint3", "Arate");
    ind = 1;            % 循环变量
    for t = 0:1/SampRate:durat
        if t <= TurnPoint1 * durat
            res(ind,1) = (Arate * amplitude / TurnPoint1 / durat * t) * sin(fre * t + PHI);
        elseif t <= TurnPoint2 * durat
            res(ind,1) = (-(Arate - 1) * amplitude / (TurnPoint2 - TurnPoint1) / durat * t + ...
                (Arate * TurnPoint2 - TurnPoint1) * amplitude / (TurnPoint2 - TurnPoint1)) * ...
                sin(fre * t + PHI);
        elseif t <= TurnPoint3 * durat
            res(ind,1) = amplitude * sin(fre * t + PHI);
        else
            res(ind,1) = (amplitude / (1 - TurnPoint3) / durat * (durat - t)) * ...
                sin(fre * t + PHI);
        end
        ind = ind + 1;
    end 
end